require("lua-xwrt.addon.string")
require("lua-xwrt.addon.uci")
require("lua-xwrt.html.form")
require("lua-xwrt.xwrt.translator")
require("lua-xwrt.addon.io")
--local json = require("json")

local string = string
local io = io
local os = os
local pairs, ipairs = pairs, ipairs
local table = table
local uci = uci
local util = util
local string = string
local type = type
local print = print
local tostring, tonumber = tostring, tonumber
local formClass = formClass
local htmlhmenuClass = htmlhmenuClass
local tr = tr
local __MENU = __MENU
local __FORM = __FORM
local __ENV = __ENV
local ssl = ssl
local peer = {	
		"type",
		"context",
		"callingpres",
		"deny",
		"permit",
		"secret",
		"md5secret",
		"dtmfmode",
		"canreinvite",
		"nat",
		"callgroup",
		"pickupgroup",
		"language",
		"disallow",
		"allow",
		"insecure",
		"trustrpid",
		"progressinband",
		"promiscredir",
		"useclientcode",
		"accountcode",
		"setvar",
		"callerid",
		"amaflags",
		"call-limit",
		"allowoverlap",
		"allowsubscribe",
		"allowtransfer",
		"subscribecontext",
		"videosupport",
		"maxcallbitrate",
		"mailbox",
		"username",
--		"template",
		"fromdomain",
		"regexten",
		"fromuser",
		"host",
		"port",
		"qualify",
		"defaultip",
		"rtptimeout",
		"rtpholdtimeout",
		"sendrpid",
		"outboundproxy",

		"rfc2833compensate",
		"t38pt_usertpsource",

		"contactpermit",
		"contactdeny"
}

--print("crea el modulo<br>")

module("lua-xwrt.ipbx-mini")
local newMenu = htmlhmenuClass.new("submenu")

function template_menu(menu)
	local menu = menu or htmlhmenuClass.new("submenu")
	uci.foreach("asterisk","template", 
		function (t)
			print(t.name)
			menu:add(t.name, "ipbx.sh?option=extensions&template="..t.name)
		end)
	return menu
end

function devices_menu(menu)
	local menu = menu or htmlhmenuClass.new("submenu")
	uci.foreach("asterisk","device", 
		function (t)
--			print(t[".name"])
			menu:add(t[".name"], "ipbx.sh?option=extensions&dev_selected="..t[".name"])
		end)
	return menu
end


__MENU.IPBX:add("Core","ipbx.sh?option=core")
--__MENU.IPBX:add("Service","ipbx.sh?option=service")
__MENU.IPBX:add("Dial Plan")
__MENU.IPBX["Dial Plan"] = htmlhmenuClass.new("submenu")
__MENU.IPBX["Dial Plan"]:add("Context", "algo")
__MENU.IPBX:add("Extensions")
__MENU.IPBX.Extensions = devices_menu() -- htmlhmenuClass.new("submenu")
--__MENU.IPBX.Extensions:add("Templates","ipbx.sh?option=templates")
--__MENU.IPBX.Extensions.Templates = htmlhmenuClass.new("submenu")
--__MENU.IPBX.Extensions.Templates:add("List","ipbx.sh?option=templates")
--template_menu(__MENU.IPBX.Extensions.Templates)
--__MENU.IPBX.Extensions:add("Extensions","ipbx.sh?option=extensions")
--__MENU.IPBX.Extensions.Extensions= htmlhmenuClass.new("submenu")
--__MENU.IPBX.Extensions.Extensions:add("List","ipbx.sh?option=extensions")
__MENU.IPBX:add("Numbers","ipbx.sh?option=numbers")
__MENU.IPBX:add("Providers")
__MENU.IPBX.Providers = htmlhmenuClass.new("submenu")
__MENU.IPBX.Providers:add("Outgoing","ipbx.sh?option=outgoing")
__MENU.IPBX.Providers:add("Incoming","ipbx.sh?option=incoming")
__MENU.IPBX:add("Dial Plan","ipbx.sh?option=dialplan")


local newMenu = htmlhmenuClass.new("submenu")

function info(form)
	local forms = {}
	if form == nil then
		form = formClass.new(tr("ipbx_info#Info Pannel"),true)
	else
		form:Add("subtitle",tr("ipbx_info#Info Pannel"))
	end
	form:Add("text_line","pepep",[[<table align="center" width=600>
<tr valign="top"><td>
<table align="left">
<tr><td colspan="2"><h2>Asterisk&trade; AJAM Demo</h2></td>
<tr><td>Username:</td><td><input id="username"></td></tr>
<tr><td>Secret:</td><td><input type="password" id="secret"></td></tr>
	<tr><td colspan=2 align="center">
	  <div id="statusbar">
		<span style="margin-left: 4px;font-weight:bold">&nbsp;</span>
	  </div>
	</td></tr>

	<tr><td><input type="submit" id="login" value="Login" onClick="doLogin()"></td>
	<td><input type="submit" id="logoff" value="Logoff" disabled=1 onClick="doLogoff()"></td></tr>
</table>
</td><td valign='bottom'>
<table>
<div style="margin-left:10;margin-right:50;margin-top:10;margin-bottom:20">
<i>This is a demo of the Asynchronous Javascript Asterisk Manager interface.  You can login with a
valid, appropriately permissioned manager username and secret.</i>
</div>
<tr>
	<td><input type="submit" onClick="doStatus()" id="refresh" value="Refresh"></td>
	<td><input type="submit" onClick="doTransfer()" id="transfer" value="Transfer..."></td>
	<td><input type="submit" onClick="doHangup()" id="hangup" value="Hangup"></td>
</tr>
</table>
</td></tr>
<tr><td colspan=2>
		<div id="channellist" class="chanlist">
		</div>
	</td></tr>
<tr><td align="center" colspan=2>
	<font size=-1><i>
		Copyright (C) 2006 Digium, Inc.  Asterisk and Digium are trademarks of Digium, Inc.
	</i></font>
</td></tr>
</table>
]])
	return form
end

function core(form)
	local forms = {}
	if form == nil then
		form = formClass.new(tr("ipbx_core#Core Service"))
	else
		form:Add("subtitle",tr("ipbx_core#Core Service"))
	end
	form:Add("service","ipbx.service.enable","asterisk",tr("ipbx_var_service#Service"),"")
	form["ipbx.service.enable"].options:Add("service","asterisk")
	form["ipbx.service.enable"].options:Add("init","asterisk")
	form:Add("subtitle", "PBX Settings")
--[[
	form:Add("select","asterisk.pbx.protocol", uci.get("asterisk",name,"protocol"), tr("ipbx_dev_protocol#Protocol"), "string")
	form["asterisk."..name..".protocol"].options:Add("SIP","SIP")
	form["asterisk."..name..".protocol"].options:Add("IAX2","IAX2")
	form["asterisk."..name..".protocol"].options:Add("ZAP","ZAP")
	form:Add("select",
]]
	return form
end

function showDevices(section)
	local htmlStr = [[<script>
function changBackground(obj){
	obj.prevColor = obj.style.backgroundColor;
	obj.style.backgroundColor="#ccc";
}
function restoreBackground(obj){
	obj.style.backgroundColor = obj.prevColor;
}
</script>
<div id="devMenu" style="float:left;">
<ul>
<script>
	var height = document.getElementById("content").clientHeight;
	height-=252;
	if (height < 150 ) height = 150;
	document.getElementById("devMenu").style.height=height+"px";
</script>
]]
	__MENU:text()
	uci.foreach("asterisk", section, function(t)
			local name = t[".name"]
			local rname = name
			if section == "template" then name = t.name end
			if __FORM["dev_selected"] == nil then
				__FORM["dev_selected"] = rname
			end
			if __FORM["dev_selected"] == rname then
				htmlStr = htmlStr .. "<li class='selected'>"
			else
				htmlStr = htmlStr .. "<li>"
			end
			htmlStr = htmlStr .. "<a href='"..__ENV.SCRIPT_NAME.."?dev_selected="..rname.."&"..__MENU.selected.."'>"..name.."</a></li>\n"
		end)
	htmlStr = htmlStr.."</ul></div><!-- devMenu -->\n"
--[[
	uci.foreach("asterisk", section, 
		function(t)
			htmlStr = htmlStr.."<div style='float:left;border: 1px solid red;'>\n"
			htmlStr = htmlStr.."<table>\n"
			for l, k in ipairs(peer) do
				if t[k] then
				htmlStr = htmlStr.."<tr>"
				htmlStr = htmlStr.."<td>"..k.."</td>"
				htnlStr = htmlStr.."<td><input type='text' name='"..k.."' value='"..t[k].."' /></td>"
				htmlStr = htmlStr.."</tr>\n"
			end
			htmlStr = htmlStr.."</table>\n"
			htmlStr = htmlStr.."</div>\n"
		end)
]]
	return htmlStr
end

function templates(form)
	local forms = {}
	if form == nil then
		form = formClass.new(tr("ipbx_extenTemplates#Templates"),true)
	else
		form:Add("subtitle",tr("ipbx_extenTemplates#Templates"),true)
	end
	form:Add("text_line","extensions",showDevices("template"),"pepe")
	local rname = __FORM.dev_selected
	form:Add("text","asterisk."..rname..".name",uci.get("asterisk",rname,"name"), tr("ipbx_extenName#Name"),"")
	return form
end
	
function extensions(form)
	local forms = {}
	
	if __FORM["dev_selected"] ~= nil then
		form = exten_conf(form)
	else
		form = select_extension(form)
	end
	return form
end

function select_extension(form)
	if form == nil then
		form = formClass.new(tr("ipbx_extensions#Extension"),true)
	else
		form:Add("subtitle",name..tr("ipbx_extensions#Extension"),true)
	end
	local str = ""
	for k, v in pairs(__FORM) do
		str = str..string.format("- '%s'<=>'%s'<br>\r\n",k,v)
	end
	form:Add("text_line","algoextensions", str, "pepon")
	form:Add("text_line","extensions",showDevices("device"),"pepe")
	return form
end

function exten_conf(form)
	local forms = {}
	local name = __FORM["dev_selected"]
	local tcontext = uci.get_type("asterisk", "context")
	
	local title = string.format("%s: %s",tr("ipbx_configure#Configure"),__FORM["dev_selected"])
	if form == nil then
		form = formClass.new(title)
	else
		form:Add("subtitle",title)
	end
	form:Add("select","asterisk."..name..".protocol", uci.get("asterisk",name,"protocol"), tr("ipbx_dev_protocol#Protocol"), "string")
	form["asterisk."..name..".protocol"].options:Add("SIP","SIP")
	form["asterisk."..name..".protocol"].options:Add("IAX2","IAX2")
	form["asterisk."..name..".protocol"].options:Add("ZAP","ZAP")
	form:Add("text","asterisk."..name..".callerIDnum", uci.get("asterisk",name,"callerIDnum"), tr("ipbx_dev_callerIDnum#Caller ID Number"), "string")
	form:Add("text","asterisk."..name..".callerIDname", uci.get("asterisk",name,"callerIDname"), tr("ipbx_dev_callerID#Caller ID Name"), "string")

	form:Add("select","asterisk."..name..".context", uci.get("asterisk",name,"context"), tr("ipbx_dev_context#Context"), "string")
	for k,t in pairs(tcontext) do
		form["asterisk."..name..".context"].options:Add(t[".name"],t[".name"])
	end


	form:Add("subtitle",tr("ipbx_dev_security#Security"))
	form:Add("text","asterisk."..name..".name", uci.get("asterisk",name,"name"), tr("ipbx_dev_name#Username"), "string")
	form:Add("text","asterisk."..name..".secret", uci.get("asterisk",name,"secret"), tr("ipbx_dev_secret#Password"), "string")
	form:Add("text","asterisk."..name..".host", uci.get("asterisk",name,"host"), tr("ipbx_dev_host#Host"), "string", "width:98%", "onfocus=\"alert('aca esta')\"; onBlur=\"alert(this.value)\";")
	form:Add("text","asterisk."..name..".deny", uci.get("asterisk",name,"deny"), tr("ipbx_dev_host#Deny"), "string", "width:98%")
	form:Add("text","asterisk."..name..".permit", uci.get("asterisk",name,"permit"), tr("ipbx_dev_host#Permit"), "string", "width:98%")


	form:Add("subtitle",tr("ipbx_dev_channelsetting#Channel Settings"))
	form:Add("select","asterisk."..name..".type", uci.get("asterisk",name,"type"), tr("ipbx_dev_calldirection#Call Direction"), "string")
	form["asterisk."..name..".type"].options:Add("user","Inbound")
	form["asterisk."..name..".type"].options:Add("peer","Outbound")
	form["asterisk."..name..".type"].options:Add("friend","Inbound/Outbound")


	form:Add("text","asterisk."..name..".dtmfmode", uci.get("asterisk",name,"dtmfmode"), tr("ipbx_dev_secret#DTMF Mode"), "string")
--	form:Add("text","asterisk."..name..".disallow", uci.get("asterisk",name,"disallow"), tr("ipbx_dev_disallow#Disallow Codecs"), "string")
--	form:Add("text","asterisk."..name..".allow", uci.get("asterisk",name,"allow"), tr("ipbx_dev_allow#Allow Codecs"), "string")
	form:Add("text","asterisk."..name..".nat", uci.get("asterisk",name,"nat"), tr("ipbx_dev_nat#NAT"), "string")
	form:Add("text","asterisk."..name..".canreinvite", uci.get("asterisk",name,"canreinvite"), tr("ipbx_dev_canreinvite#Can Reinvite"), "string")
	form:Add("text","asterisk."..name..".qualify", uci.get("asterisk",name,"qualify"), tr("ipbx_dev_qualify#Qualify"), "string")
--	form:Add("text","asterisk."..name..".videosupport", uci.get("asterisk",name,"videosupport"), tr("ipbx_dev_videosupport#Video Support"), "string")
--	form:Add("text","asterisk."..name..".context", uci.get("asterisk",name,"context"), tr("ipbx_dev_context#Context"), "string")
	local str = ""
	local sep = ""

	local tdis = uci.get("asterisk", name, "disallow")
	if tdis then
		for k, line in pairs(tdis) do
			for code in string.gmatch(line,"%S+") do
				str = sep..str .. code
				sep = ", "
			end
		end
	end
	form:Add("text","asterisk."..name..".disallow", str, tr("ipbx_dev_disallow#Disallow"), "string", "width: 98%;", [[onFocus='overlay();']]) 

--	form:Add("list_add", "asterisk."..name..".disallow", uci.get("asterisk",name,"disallow"),tr("ipbx_dev_disallow#Disallow"),"string","width: 100%")
--	form:Add("list_add", "asterisk."..name..".allow", uci.get("asterisk",name,"allow"),tr("ipbx_dev_allow#Allow"),"string","width: 100%")
--	form:Add("text","asterisk."..name..".secret", uci.get("asterisk",name,"secret"), tr("ipbx_dev_secret#Secret"), "string")
	return form
end

function numbers(form)
	local forms = {}
	if form == nil then
		form = formClass.new(tr("ipbx_phones#Phones"))
	else
		form:Add("subtitle",tr("ipbx_phones#Phones"))
	end
	form:Add("select","asterisk.internal.digits", uci.get("asterisk","digists","type"), tr("ipbx_dev_calldirection#Call Direction"), "string")
	return form
end

function outgoing(form)
	local forms = {}
	if form == nil then
		form = formClass.new(tr("ipbx_providers#Providers"))
	else
		form:Add("subtitle",tr("ipbx_providers#Providers"))
	end
	form:Add("text_line","asdfa",util.table2string(__MENU,"<br>"))
	return form
end

function dialplan(form)
	local forms = {}
	if form == nil then
		form = formClass.new(tr("ipbx_dialplan#Dials"))
	else
		form:Add("subtitle",tr("ipbx_dialplan#Dials"))
	end
	return form
end
